package com.catsic.practice.listener;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhangzf
 * @CreateTime: 2025-10-31  17:03
 * @Description: 动态分配任务监听器
 */
@Slf4j
@Component
public class NextAssigneeListener implements ExecutionListener {

    // 定义节点间的流转关系（正向和逆向）
    private static final Map<String, String> NEXT_NODE_MAPPING = new HashMap<>();
    private static final Map<String, String> ROLLBACK_NODE_MAPPING = new HashMap<>();

    static {
        // 正向流转关系
        NEXT_NODE_MAPPING.put("policyRegulationsApproval", "responsibleDepartmentApproval");
        NEXT_NODE_MAPPING.put("responsibleDepartmentApproval", "agencyResponse");
        NEXT_NODE_MAPPING.put("agencyResponse", "responsibleDepartmentReview");
        NEXT_NODE_MAPPING.put("responsibleDepartmentReview", "departmentLeaderApproval");
        NEXT_NODE_MAPPING.put("departmentLeaderApproval", "hotlineLeaderApproval");

        // 逆向流转关系（回退目标）
        ROLLBACK_NODE_MAPPING.put("policyRegulationsApproval", "policyRegulationsApproval"); // 回退到自身
        ROLLBACK_NODE_MAPPING.put("responsibleDepartmentApproval", "policyRegulationsApproval");
        ROLLBACK_NODE_MAPPING.put("agencyResponse", "responsibleDepartmentApproval");
        ROLLBACK_NODE_MAPPING.put("responsibleDepartmentReview", "agencyResponse");
        ROLLBACK_NODE_MAPPING.put("departmentLeaderApproval", "responsibleDepartmentReview");
        ROLLBACK_NODE_MAPPING.put("hotlineLeaderApproval", "departmentLeaderApproval");
    }


    @Override
    public void notify(DelegateExecution execution) {
        String currentActivityId = execution.getCurrentActivityId();
        String nextAssignee = (String) execution.getVariable("nextAssignee");
        String rejectReason = (String) execution.getVariable("rejectReason");

        log.info("执行监听器 - 当前节点: {}, 下一审批人: {}, 回退原因: {}",
                currentActivityId, nextAssignee, rejectReason);

        // 判断是正向流转还是回退
        if ("rollback".equals(rejectReason)) {
            // 回退流程 - 需要设置回退目标节点的审批人
            handleRollbackAssignment(execution, currentActivityId, nextAssignee);
        } else {
            // 正向流程 - 设置下一节点的审批人
            handleForwardAssignment(execution, currentActivityId, nextAssignee);
        }

        // 清空临时变量（保留rejectReason用于流程判断）
        execution.removeVariable("nextAssignee");
    }

    /**
     * 处理正向流转的审批人分配
     */
    private void handleForwardAssignment(DelegateExecution execution, String currentActivityId, String nextAssignee) {
        if (nextAssignee == null) {
            log.warn("正向流转时未指定下一审批人，当前节点: {}", currentActivityId);
            return;
        }

        String nextNodeId = NEXT_NODE_MAPPING.get(currentActivityId);
        if (nextNodeId != null) {
            setAssigneeForNode(execution, nextNodeId, nextAssignee);
            log.info("正向流转 - 为节点 {} 设置审批人: {}", nextNodeId, nextAssignee);
        }
    }

    /**
     * 处理回退流程的审批人分配
     */
    private void handleRollbackAssignment(DelegateExecution execution, String currentActivityId, String nextAssignee) {
        String rollbackNodeId = ROLLBACK_NODE_MAPPING.get(currentActivityId);

        // 如果回退时指定了新的审批人，使用新审批人；否则使用原审批人或默认审批人
        String actualAssignee = nextAssignee != null ? nextAssignee : getDefaultAssigneeForRollback(rollbackNodeId);

        if (rollbackNodeId != null && actualAssignee != null) {
            setAssigneeForNode(execution, rollbackNodeId, actualAssignee);
            log.info("回退流转 - 为回退目标节点 {} 设置审批人: {}", rollbackNodeId, actualAssignee);
        } else {
            log.warn("回退流转 - 无法确定回退目标节点或审批人, 当前节点: {}, 回退目标: {}",
                    currentActivityId, rollbackNodeId);
        }
    }

    /**
     * 为指定节点设置审批人
     */
    private void setAssigneeForNode(DelegateExecution execution, String nodeId, String assignee) {
        switch (nodeId) {
            case "policyRegulationsApproval":
                execution.setVariable("policyRegulationsAssignee", assignee);
                break;
            case "responsibleDepartmentApproval":
                execution.setVariable("responsibleDepartmentAssignee", assignee);
                break;
            case "agencyResponse":
                execution.setVariable("agencyAssignee", assignee);
                break;
            case "responsibleDepartmentReview":
                execution.setVariable("reviewAssignee", assignee);
                break;
            case "departmentLeaderApproval":
                execution.setVariable("leaderAssignee", assignee);
                break;
            case "hotlineLeaderApproval":
                execution.setVariable("hotlineLeaderAssignee", assignee);
                break;
            default:
                log.warn("未知的节点ID: {}", nodeId);
        }
    }

    /**
     * 获取回退时的默认审批人（可根据业务规则调整）
     */
    private String getDefaultAssigneeForRollback(String rollbackNodeId) {
        // 这里可以根据业务需求设置默认审批人
        // 例如：从数据库查询、使用固定用户等
        switch (rollbackNodeId) {
            case "policyRegulationsApproval":
                return "policy_default_user";
            case "responsibleDepartmentApproval":
                return "responsible_default_user";
            case "agencyResponse":
                return "agency_default_user";
            case "responsibleDepartmentReview":
                return "review_default_user";
            case "departmentLeaderApproval":
                return "leader_default_user";
            default:
                return null;
        }
    }

    /**
     * 获取下一节点信息（用于前端展示）
     */
    public static String getNextNodeInfo(String currentTaskId, boolean isRollback) {
        if (isRollback) {
            String rollbackNode = ROLLBACK_NODE_MAPPING.get(currentTaskId);
            return rollbackNode != null ? "回退至: " + getNodeName(rollbackNode) : "无法回退";
        } else {
            String nextNode = NEXT_NODE_MAPPING.get(currentTaskId);
            return nextNode != null ? "下一节点: " + getNodeName(nextNode) : "流程结束";
        }
    }

    private static String getNodeName(String nodeId) {
        switch (nodeId) {
            case "policyRegulationsApproval": return "政策法规科审批";
            case "responsibleDepartmentApproval": return "责任科室审批";
            case "agencyResponse": return "承办机构答复";
            case "responsibleDepartmentReview": return "责任科室复核";
            case "departmentLeaderApproval": return "责任科室主管领导意见";
            case "hotlineLeaderApproval": return "12328热线分管领导审批";
            default: return nodeId;
        }
    }
}
